package com.hzit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hzit.dto.StudentDTO;
import com.hzit.entity.Classes;
import com.hzit.entity.Student;
import com.hzit.entity.StudentExample;
import com.hzit.mapper.ClassesMapper;
import com.hzit.mapper.StudentMapper;
import com.hzit.service.StudentService;
import com.hzit.util.PageResult;
import com.hzit.vo.StudentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Struct;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class StudentServiceImpl implements StudentService {
	@Autowired
	private StudentMapper studentMapper;
	@Autowired
	private ClassesMapper classesMapper;
	//1. 列表学生
	@Override
	public List<Student> findAll() {
		return studentMapper.selectByExample(null);
	}

	//2. 条件查询带分页
	@Override
	public PageResult<StudentDTO> search(Integer page, Integer pageSize, StudentVo vo) {
		// 2.1 开始分页
		PageHelper.startPage(page,pageSize);
		// 2.2 开始条件查询
		StudentExample example = new StudentExample();
		StudentExample.Criteria criteria = example.createCriteria();
		// 2.3 封装查询条件并开始查询
		if(vo != null){
			if(StrUtil.isNotBlank(vo.getSname())){
				criteria.andSnameLike("%" + vo.getSname() + "%");
			}
			if(StrUtil.isNotBlank(vo.getAddr())){
				criteria.andAddrLike("%" + vo.getAddr() + "%");
			}
			if(vo.getCid() != null && vo.getCid() != 0){
				criteria.andCidEqualTo( vo.getCid());
			}
		}
		List<Student> students = studentMapper.selectByExample(example);
		Page<Student> studentPage = (Page<Student>) students;
		// 2.4 将集合中的student设置
		List<StudentDTO> collect = studentPage.getResult().stream().map(m -> {
			StudentDTO dto = new StudentDTO();
			// 将m（Student）对象根据属性名（忽略大小写）复制到vo对象中
			BeanUtil.copyProperties(m, dto, true);
			Classes classes = classesMapper.selectByPrimaryKey(m.getCid());
			dto.setCname(classes.getCname());
			return dto;
		}).collect(Collectors.toList());

		return new PageResult<>(studentPage.getTotal(),collect);
	}

	//3. 根据学生编号查询学生
	@Override
	public StudentDTO findById(Long id) {
		Student student = studentMapper.selectByPrimaryKey(id);
		StudentDTO dto = new StudentDTO();
		BeanUtil.copyProperties(student,dto);
		Classes classes = classesMapper.selectByPrimaryKey(student.getCid());
		dto.setCname(classes.getCname());
		return dto;

	}

	@Override
	public void insert(Student student) {
		studentMapper.insert(student);
	}

	@Override
	public void update(Student student) {
		studentMapper.updateByPrimaryKey(student);
	}
}
